package com.excel.strategy;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description ExcelStyleTool
 * @Author fuhao
 * @CreateTime 2024/10/16 17:20
 */
public class ExcelStyleTool {


    private ExcelStyleTool() {
        throw new IllegalStateException("Utility class");
    }


    public static WriteFont defaultFontStyle() {
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints(Short.valueOf((short) 9));
        headWriteFont.setColor(IndexedColors.BLACK.getIndex());
        headWriteFont.setFontName("宋体");
        headWriteFont.setBold(true);

        return headWriteFont;
    }

    public static WriteCellStyle defaultContentCellStyle() {
        // 设置内容样式
        WriteCellStyle contentStyle = new WriteCellStyle();
        contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontName("宋体");
        contentWriteFont.setFontHeightInPoints(Short.valueOf((short) 9));
        contentWriteFont.setBold(false);
        contentStyle.setWriteFont(contentWriteFont);

        return contentStyle;
    }


    public static Short getDynamicHeadStyle(Head head) {
        if (StringUtils.isNotBlank(head.getFieldName()) && head.getFieldName().startsWith("CommonConstant.OPTION_NAME_ONE")) {
            return IndexedColors.LIGHT_GREEN.getIndex();
        }
        int headIndex = head.getColumnIndex();
        if (headIndex < 12) {
            return IndexedColors.PALE_BLUE.getIndex();
        }
        // 利用下标奇偶数来切换颜色
        if (CollectionUtils.isNotEmpty(head.getHeadNameList())) {
            String headName = head.getHeadNameList().get(0);
            Pattern pattern = Pattern.compile("\\d+");
            Matcher matcher = pattern.matcher(headName);
            if (!matcher.find()) {
                return IndexedColors.PALE_BLUE.getIndex();
            }
            Integer result = Integer.valueOf(matcher.group());
            if (isEven(result)) {
                return IndexedColors.PALE_BLUE.getIndex();
            } else {
                return IndexedColors.LIGHT_GREEN.getIndex();
            }
        }
        return IndexedColors.PALE_BLUE.getIndex();
    }

    // 判断是否为偶数的方法
    public static boolean isEven(int num) {
        return num % 2 == 0;
    }

}
